<template>
  <section class="page article-list-page">
    <h1 class="page-title">文章列表</h1>

    <div class="card mb-3">
      <div class="card-body">
        <div class="row g-3 align-items-end">
          <div class="col-md-4">
            <label class="form-label">关键词</label>
            <el-input v-model="query.keyword" placeholder="请输入标题关键词" clearable />
          </div>
          <div class="col-md-4">
            <label class="form-label">分类</label>
            <el-select v-model="query.category" placeholder="请选择分类" clearable @change="onCategoryChange">
              <el-option label="全部" value="" />
              <el-option label="技术" value="tech" />
              <el-option label="生活" value="life" />
              <el-option label="新闻" value="news" />
            </el-select>
          </div>
          <div class="col-md-4 d-flex gap-2">
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-body">
        <el-table :data="list" stripe style="width: 100%" v-loading="loading" empty-text="暂无数据">
          <el-table-column prop="title" label="标题" min-width="220" />
          <el-table-column prop="summary" label="摘要" min-width="260">
            <template #default="{ row }">
              <el-tooltip :content="row.summary" placement="top" :disabled="!row.summary">
                <span class="desc-ellipsis">{{ row.summary || "—" }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="categoryName" label="分类" width="120" align="center" />
          <el-table-column prop="author" label="作者" width="120" align="center" />
          <el-table-column label="发布时间" width="180" align="center">
            <template #default="{ row }">
              {{ row.publishedAt }}
            </template>
          </el-table-column>
          <el-table-column prop="views" label="浏览量" width="120" align="center" />
          <el-table-column prop="likes" label="点赞" width="100" align="center" />
          <el-table-column prop="comments" label="评论" width="100" align="center" />
        </el-table>

        <div class="pagination-section">
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
// 模拟文章列表接口，支持关键词与分类筛选、分页
import { ref, reactive, onMounted, computed } from "vue";

interface Article {
  id: string;
  title: string;
  category: "tech" | "life" | "news";
  categoryName: string;
  author: string;
  publishedAt: string;
  // 扩展的丰富字段
  summary: string;
  tags: string[];
  views: number;
  likes: number;
  comments: number;
  readingTime: number; // 单位：分钟
}

const query = reactive({ keyword: "", category: "" as "" | "tech" | "life" | "news" });
const loading = ref(false);
const list = ref<Article[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(5);

const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)));

function mockFetchArticles(params: {
  keyword: string;
  category: string;
  page: number;
  pageSize: number;
}): Promise<{ list: Article[]; total: number }> {
  return new Promise((resolve) => {
    setTimeout(() => {
      const cats = ["tech", "life", "news"] as const;
      const authors = ["张三", "李四", "王五", "赵六", "孙七"];
      const tagPool = ["前端", "后端", "AI", "云原生", "生活方式", "职场", "热点", "行业观察"];
      const titles = [
        "深入理解Vue组合式API",
        "NestJS实战：从入门到落地",
        "前端性能优化的10个技巧",
        "生活与工作：时间管理之道",
        "科技新闻速递：本周看点",
        "AI应用案例解析",
        "微服务与容器化最佳实践",
        "产品思考：从需求到交付",
      ];
      const summaries = [
        "本文从架构设计出发，解析关键实现细节与常见坑位。",
        "围绕工程化与测试，给出可复用的实践方案。",
        "覆盖数据处理、交互设计与体验优化的综合指南。",
        "从实际场景出发，拆解问题与解决方案。",
        "精选本周行业热点，并给出简要点评。",
        "结合案例展示AI在业务中的落地路径。",
        "聚焦服务拆分与部署治理，提供实用建议。",
        "梳理从需求洞察到产品交付的完整流程。",
      ];
      const rand = (min: number, max: number) => Math.round(min + Math.random() * (max - min));
      const pickTags = () => {
        const shuffled = [...tagPool].sort(() => Math.random() - 0.5);
        return shuffled.slice(0, rand(2, 4));
      };

      const ALL: Article[] = Array.from({ length: 35 }).map((_, i) => {
        const c = cats[i % cats.length];
        const cn = c === "tech" ? "技术" : c === "life" ? "生活" : "新闻";
        const titleSeed = titles[i % titles.length];
        const summarySeed = summaries[i % summaries.length];

        const published = new Date(Date.now() - Math.random() * 1000 * 60 * 60 * 24 * 60); // 近两个月随机
        const yyyy = published.getFullYear();
        const mm = String(published.getMonth() + 1).padStart(2, "0");
        const dd = String(published.getDate()).padStart(2, "0");
        const hh = String(published.getHours()).padStart(2, "0");
        const mi = String(published.getMinutes()).padStart(2, "0");

        return {
          id: `a_${i + 1}`,
          title: `${titleSeed} · 示例 ${i + 1}`,
          category: c,
          categoryName: cn,
          author: authors[i % authors.length],
          publishedAt: `${yyyy}-${mm}-${dd} ${hh}:${mi}`,
          summary: `${summarySeed}（编号 ${i + 1}）。`,
          tags: pickTags(),
          views: rand(50, 8000),
          likes: rand(0, 1200),
          comments: rand(0, 300),
          readingTime: rand(2, 15),
        };
      });

      let filtered = ALL;
      if (params.keyword) {
        filtered = filtered.filter((x) => x.title.includes(params.keyword));
      }
      if (params.category) {
        filtered = filtered.filter((x) => x.category === params.category);
      }

      const start = (params.page - 1) * params.pageSize;
      const sliced = filtered.slice(start, start + params.pageSize);
      resolve({ list: sliced, total: filtered.length });
    }, 700);
  });
}

async function fetchList() {
  loading.value = true;
  const res = await mockFetchArticles({
    keyword: query.keyword,
    category: query.category,
    page: page.value,
    pageSize: pageSize.value,
  });
  list.value = res.list;
  total.value = res.total;
  loading.value = false;
}

function search() {
  page.value = 1;
  fetchList();
}
function reset() {
  query.keyword = "";
  query.category = "";
  search();
}

function onCategoryChange() {
  page.value = 1;
  fetchList();
}
function changePage(p: number) {
  page.value = p;
  fetchList();
}

function handleSizeChange(size: number) {
  pageSize.value = size;
  page.value = 1;
  fetchList();
}

onMounted(fetchList);
</script>

<style scoped lang="scss">
.page {
  padding: 16px;
}
.page-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
}
.desc-ellipsis {
  display: inline-block;
  max-width: 420px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: bottom;
  color: #606266;
}
.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-light);
}
</style>
